﻿using System;
using System.Collections.Generic;
using PSE.Deployment.ConfigurationManager.Engine.Logging;
using PSE.Deployment.SetupBase.Configuration;
using PSE.Deployment.SetupBase.Parameter;

namespace PSE.Deployment.ConfigurationManager.Engine.Operations
{
	/// <summary>
	/// Classe de operacoes de Registro Windows, herda de BaseOperations
	/// </summary>
	public class RegistryOperations : BaseOperations
	{
        public RegistryOperations(SetupParameter parameter)
            : base(parameter)
		{

		}

		/// <summary>
		/// Metodo responsavel por atualizar dados informados no registro do Windows
		/// </summary>
		/// <param name="regKeys">Chaves a serem alteradas</param>
		public bool Save(List<RegistryKey> regKeys)
		{
            bool isSaved = false;
            
            foreach (RegistryKey key in regKeys)
			{
                base.EncryptTags(key.Values);

                if (!key.HasAnyPropertyChanged)
                    continue;
                
                try
				{
					Microsoft.Win32.RegistryKey windowsKey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(key.Name);

                    foreach (RegistryValue regValue in key.Values)
					{
                        if (!regValue.HasChanges)
                            continue;

						try
						{
							OperationLog.Write("Registry key (" + regValue.Name + ") saved successfully with the value (" + regValue.Value + ")");
							
                            windowsKey.SetValue(regValue.Name, regValue.Value, regValue.RegistryValueKind);

                            isSaved = true;
						}
						catch (Exception ex)
						{
							OperationLog.Write("Error while trying to save Registry key (" + regValue.Name + ") with the value (" + regValue.Value + ")", ex);
						}
					}

                    key.HasAnyPropertyChanged = false;

					OperationLog.Write("Registry configuration file (" + key.Name + ") saved successfully");
				}
				catch (Exception ex)
				{
					OperationLog.Write("Error while trying to save Registry configuration file (" + key.Name + ")", ex);
				}
			}

            return isSaved;
		}       
	}
}